package com.minio.util;

import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.Data;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description： minio客户端工具类
 */
@Component
public class MinioUtils {
    private static Logger logger = LoggerFactory.getLogger(MinioUtils.class);
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Data
    public class ObjectItem {
        private String objectName;
        private Long size;
    }

    /**
     * description: 判断bucket是否存在，不存在则创建
     *
     * @return: void
     */
    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            logger.error("判断bucket是否存在异常", e);
        }
    }

    /**
     * 创建存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            logger.error("创建bucket异常", e);
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            logger.error("删除bucket存在异常", e);
            return false;
        }
        return true;
    }

    /**
     * description: 上传文件
     *
     * @param multipartFile
     * @return: java.lang.String
     */
    public List<String> upload(MultipartFile[] multipartFile) {
        List<String> names = new ArrayList<>(multipartFile.length);

        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                logger.error("判断bucket不存在，请检查是否创建");
                return null;
            }
        } catch (Exception e) {
            logger.error("bucket是否存在发生异常", e);
            return null;
        }

        for (MultipartFile file : multipartFile) {
            String fileName = file.getOriginalFilename();
            String[] split = fileName.split("\\.");
            StringBuffer newFileName = new StringBuffer();  //文件路径以文件后缀名定义+新的文件名称，进行存放
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String day = dateFormat.format(date);

            if (split.length > 1) {
                newFileName.append(split[1] + "/" + day + "_" + fileName);
            } else {
                newFileName.append(day + "_" + fileName);
            }
            InputStream in = null;
            try {
                in = file.getInputStream();
                String contentType = file.getContentType();
                minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(String.valueOf(newFileName)).stream(in, in.available(), -1).contentType(contentType).build());
            } catch (Exception e) {
                logger.error("上传文件发生异常", e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        logger.error("关闭文件流发生异常", e);
                    }
                }
            }
            names.add(String.valueOf(newFileName));
        }
        return names;
    }

    /**
     * description: 下载文件
     *
     * @param fileName
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */
    public ResponseEntity<byte[]> download(String fileName) {
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            out = new ByteArrayOutputStream();
            int count = IOUtils.copy(in, out);
            //封装返回值
            byte[] bytes = out.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            try {
                headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                logger.error("文件格式转码异常", e);
                return null;
            }
            headers.setContentLength(bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
            responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("下载文件发生异常", e);
            return null;
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        logger.error("关闭文件流发生异常", e);
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                logger.error("文件流处理发生异常", e);
            }
        }
        return responseEntity;
    }

    /**
     * 查看文件对象
     *
     * @param bucketName 存储bucket名称
     * @return 存储bucket内文件对象信息
     */
    public List<ObjectItem> listObjects(String bucketName) {
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        List<ObjectItem> objectItems = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                Item item = result.get();
                ObjectItem objectItem = new ObjectItem();
                objectItem.setObjectName(item.objectName());
                objectItem.setSize(item.size());
                objectItems.add(objectItem);
            }
        } catch (Exception e) {
            logger.error("查看文件对象发生异常", e);
            return null;
        }
        return objectItems;
    }

    /**
     * 删除单个文件对象
     *
     * @param fileName 文件名称
     */
    public boolean removeObject(String fileName) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                logger.error("判断bucket不存在，请检查是否创建");
                return false;
            }
        } catch (Exception e) {
            logger.error("bucket是否存在发生异常", e);
            return false;
        }

        try {
            // 删除
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
            logger.error("删除单个文件时发生异常", e);
            return false;
        }
        return true;
    }

    /**
     * 批量删除多个文件对象
     *
     * @param objects 对象名称集合
     */
    public boolean removeObjects(List<String> objects) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                logger.error("判断bucket不存在，请检查是否创建");
                return false;
            }
        } catch (Exception e) {
            logger.error("bucket是否存在发生异常", e);
            return false;
        }

        try {
            List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
            // 删除
            Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
            for (Result<DeleteError> result : results) {
                // 删除文件不存在时，不会报错
                DeleteError error = result.get();
                logger.error("Error in deleting object ,objectName= {}  ,message={}", error.objectName(), error.message());
                return false;
            }
        } catch (Exception e) {
            logger.error("删除多个文件时发生异常", e);
            return false;
        }
        return true;
    }

}
